package cc.fs.androidcode.ui.touch;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

import cc.fs.androidcode.utils.L;
import cc.fs.androidcode.utils.T;

/**
 * Created by fostion on 2015/12/9.
 *                触发点击               是否截取点击事件        处理点击事件
 * view事件传递 dispatchTouchEvent -> onInterceptTouchEvent -> onTouchEvent
 */
public class MyViewGroup extends RelativeLayout {
    public MyViewGroup(Context context) {
        super(context);
    }

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    /**
     * 点击事件进来后首先会触发的事件
     * 确定是否截取事件或者是将事件传递到子组件处理
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
//        L.e("----------MyViewGroup  dispatchTouchEvent----------------");
        boolean consume = false;
        if (onInterceptTouchEvent(ev)) {
            consume = onTouchEvent(ev);
        } else {
            if (getChildCount() > 0) {
                consume = getChildAt(0).dispatchTouchEvent(ev);
            }
        }
        return consume;
    }

    private float cX;
    private float cY;
    private float mX;
    private float mY;

    /**
     * 是否截取事件
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
//        L.e("----------MyViewGroup   onInterceptTouchEvent------------");
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            cX = ev.getX();
            cY = ev.getY();
            return true;  //第一次触碰必须截取事件否则无法获取陆续发生的事件
        }

        if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            mX = ev.getX();
            mY = ev.getY();
            float deltX = mX - cX;
            float deltY = mY - cY;

            if (Math.abs(deltX) > Math.abs(deltY)) {//横滑大于竖滑动
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
//        L.e("----------MyViewGroup  onTouchEvent------------  ");
        T.toast("事件由父 GroupView 处理 ");

        return super.onTouchEvent(ev);
    }
}
